<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="入库单编号" prop="recptCode">
        <el-input
          v-model="queryParams.recptCode"
          placeholder="请输入入库单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库单名称" prop="recptName">
        <el-input
          v-model="queryParams.recptName"
          placeholder="请输入入库单名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产工单编码" prop="workorderCode">
        <el-input
          v-model="queryParams.workorderCode"
          placeholder="请输入生产工单编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库名称" prop="warehouseName">
        <el-input
          v-model="queryParams.warehouseName"
          placeholder="请输入仓库名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['productrecpt:productrecpt:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['productrecpt:productrecpt:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['productrecpt:productrecpt:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['productrecpt:productrecpt:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productrecptList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="入库单ID" align="center" prop="recptId" />
      <el-table-column label="入库单编号" align="center" prop="recptCode" />
      <el-table-column label="入库单名称" align="center" prop="recptName" />
      <el-table-column label="生产工单编码" align="center" prop="workorderCode" />
      <el-table-column label="产品物料名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="入库日期" align="center" prop="recptDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.recptDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['productrecpt:productrecpt:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['productrecpt:productrecpt:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品入库录对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="productrecptRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
        <!-- 入库单编号 -->
        <el-col :span="7">
          <el-form-item label="入库单编号" prop="recptCode" label-width="100px">
            <el-input 
              v-model="form.recptCode" 
              placeholder="请输入入库单编号" 
              :disabled="autoGenerate" />
          </el-form-item>
        </el-col>

        <!-- 自动生成开关 -->
        <el-col :span="5">
          <el-form-item label="自动生成" label-width="80px"> <!-- 缩短标签宽度 -->
            <el-switch 
              v-model="autoGenerate" 
              active-text="是" 
              inactive-text="否" 
              @change="handleAutoGenerate" />
          </el-form-item>
        </el-col>

        <!-- 入库单名称 -->
        <el-col :span="12">
          <el-form-item label="入库单名称" prop="recptName" label-width="100px">
            <el-input v-model="form.recptName" placeholder="请输入入库单名称" />
          </el-form-item>
        </el-col> 
      </el-row>
        <el-row>
          <el-col :span="8">
             <el-form-item label="生产工单">
              <el-input placeholder="请选择生产工单" v-model="form.workorderCode"  style="width: 180px" readonly>
                <template #append>
                  <el-button :icon="Search" @click="dialogTableVisible = true"/>
                </template>
              </el-input>
              <!-- <el-button type="primary" :icon="Search"/> -->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产工单名称" prop="workorderName">
              <el-input v-model="form.workorderName" placeholder="请输入生产工单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库日期" prop="recptDate">
                  <el-date-picker
                    v-model="form.recptDate"
                    type="date"
                    placeholder="Pick a day"
                    :disabled-date="disabledDate"
                    :shortcuts="shortcuts"
                    :size="size"
                  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
      <el-tabs type="border-card" v-if="form.recptId">
        <el-tab-pane label="产品物料">
          <Pdc  :current-recptId="form.recptId"></Pdc>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-dialog v-model="dialogTableVisible" title="工单选择" width="1220" append-to-body>
         <Workorder 
      :children-status="'已确认'" 
          @selectWorkorder="handleSelectWorkorder"
        ></Workorder>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="confirmSelectWorkorder">确 定</el-button>
            <el-button @click="dialogTableVisible = false">取消</el-button>
          </div>
        </template>
    </el-dialog>
  </div>
</template>

<script setup name="Productrecpt">
import { listProductrecpt, getProductrecpt, delProductrecpt, addProductrecpt, updateProductrecpt } from "@/api/productrecpt/productrecpt"
import { Finished, Search } from '@element-plus/icons-vue'
import Workorder from '@/views/workorder/workorder/index.vue'
import Pdc from '@/views/productreceptline/productreceptline/index.vue'
const { proxy } = getCurrentInstance()
const dialogTableVisible = ref(false)
const productrecptList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    recptCode: null,
    recptName: null,
    workorderCode: null,
    warehouseName: null,
  },
  rules: {
    recptCode: [
      { required: true, message: "入库单编号不能为空", trigger: "blur" }
    ],
    itemId: [
      { required: true, message: "产品物料ID不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)
//时间日期选择相关的函数
const shortcuts = [
  {
    text: 'Today',
    value: new Date(),
  },
  {
    text: 'Yesterday',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: 'A week ago',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
      return date
    },
  },
]
const disabledDate = (time) => {
  return time.getTime() > Date.now()
}
const selectedWorkorder = ref(null);  // 存储选中的工单

// 接收子组件回传的选中工单
const handleSelectWorkorder = (workorder) => {
  console.log(workorder)
  selectedWorkorder.value = workorder;
  console.log("选中的已确认工单：", workorder);
  // 可选：选中后自动关闭弹窗
    // 关键调试：打印接收到的工单数据，确认是否有值
  console.log("父组件接收到的工单：", workorder); 
  console.log("selectedWorkorder值：", selectedWorkorder.value);
  // dialogTableVisible.value = false;
};
/** 工单选择弹窗的“确定”按钮：回填数据到表单 */
const confirmSelectWorkorder = () => {
   console.log("确认时的selectedWorkorder：", selectedWorkorder.value); 
  // 1. 校验：是否选中工单
  if (!selectedWorkorder.value) {
    proxy.$modal.msgWarning("请先选择一条已确认的生产工单");
    return;
  }

  // 2. 数据回填：将选中的工单数据映射到form中
  // 注意：字段名需与子组件返回的工单数据字段一致（如workorderId、workorderCode等）
  form.value.workorderId = selectedWorkorder.value.workorderId; // 工单ID（后端关联用）
  form.value.workorderCode = selectedWorkorder.value.workorderCode; // 工单编码（显示+搜索用）
  form.value.workorderName = selectedWorkorder.value.workorderName; // 工单名称
  // 扩展：如果工单数据包含产品信息，可直接回填产品字段（避免手动输入）
  form.value.itemId = selectedWorkorder.value.productId; // 产品ID
  form.value.itemCode = selectedWorkorder.value.productCode; // 产品编码
  form.value.itemName = selectedWorkorder.value.productName; // 产品名称
  form.value.specification = selectedWorkorder.value.productSpc; // 产品规格
  form.value.unitOfMeasure = selectedWorkorder.value.unitOfMeasure; // 产品单位
  //用来存储数量
  form.value.attr1= selectedWorkorder.value.quantity
  // 3. 关闭工单选择弹窗
  dialogTableVisible.value = false;

  // 4. 提示（可选，提升用户体验）
  proxy.$modal.msgSuccess(`已选择工单：${selectedWorkorder.value.workorderCode}`);
};
import dayjs from 'dayjs'; // 引入dayjs处理时间
// ... 其他已有引入

const autoGenerate = ref(true); // 默认“自动生成”为开启状态

// 生成入库单编号（示例规则：前缀+时间戳，如 RK-20250921195030）
const generateRecptCode = () => {
  const now = dayjs();
  return 'RK-' + now.format('YYYYMMDDHHmmss');
};
// 开关切换时，生成/清空编号
const handleAutoGenerate = (isAuto) => {
  if (isAuto) {
    // 开启自动生成 → 生成新编号
    form.value.recptCode = generateRecptCode();
  } else {
    // 关闭自动生成 → 清空编号（由用户手动输入）
    form.value.recptCode = '';
  }
};
/** 查询产品入库录列表 */
function getList() {
  loading.value = true
  listProductrecpt(queryParams.value).then(response => {
    productrecptList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    
    recptId: null,
    recptCode: null,
    recptName: null,
    workorderId: null,
    workorderCode: null,
    workorderName: null,
    itemId: null,
    itemCode: null,
    itemName: null,
    specification: null,
    unitOfMeasure: null,
    warehouseId: null,
    warehouseCode: null,
    warehouseName: null,
    locationId: null,
    locationCode: null,
    locationName: null,
    areaId: null,
    areaCode: null,
    areaName: null,
    recptDate: null,
    status: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  autoGenerate.value = true; // 重置为“自动生成”开启
  if (autoGenerate.value) {
    form.value.recptCode = generateRecptCode(); // 生成新编号
  }
  proxy.resetForm("productrecptRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recptId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加产品入库单";
  // 自动生成编号（若开关开启）
  if (autoGenerate.value) {
    form.value.recptCode = generateRecptCode();
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _recptId = row.recptId || ids.value
  getProductrecpt(_recptId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改产品入库录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["productrecptRef"].validate(valid => {
    if (valid) {
      if (form.value.recptId != null) {
        updateProductrecpt(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addProductrecpt(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _recptIds = row.recptId || ids.value
  proxy.$modal.confirm('是否确认删除产品入库录编号为"' + _recptIds + '"的数据项？').then(function() {
    return delProductrecpt(_recptIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('productrecpt/productrecpt/export', {
    ...queryParams.value
  }, `productrecpt_${new Date().getTime()}.xlsx`)
}

getList()
</script>
